package com.example.finalhomework.weather

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.webweatherapplication.weather.Weather
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

// WeatherViewModel 继承自 AndroidViewModel，用于管理和提供天气数据
class WeatherViewModel(application: Application) : AndroidViewModel(application) {
    // 使用 MutableStateFlow 来存储天气数据
    private val _weather = MutableStateFlow<Weather?>(null)
    val weather: StateFlow<Weather?> = _weather

    // fetchWeather 方法用于获取指定城市代码的天气数据
    fun fetchWeather(cityCode: String) {
        viewModelScope.launch {
            // 创建请求队列（Volley 库）
            val queue = Volley.newRequestQueue(getApplication())
            // 构建请求 URL
            val url = "http://t.weather.itboy.net/api/weather/city/$cityCode"

            Log.d("WeatherViewModel", "Fetching weather for cityCode: $cityCode")
            Log.d("WeatherViewModel", "Fetching weather from URL: $url")

            // 创建 StringRequest 请求（向指定的 URL 发送 HTTP GET 请求，并获取天气数据的响应）
            val stringRequest = StringRequest(url, { response ->
                // 使用 Gson 解析 JSON 数据
                Log.d("WeatherViewModel", "Response: $response")
                val gson = Gson()
                val weatherType = object : TypeToken<Weather>() {}.type
                val weather = gson.fromJson<Weather>(response, weatherType)
                // 更新天气数据
                _weather.value = weather
                Log.d("WeatherViewModel", "Weather data updated: $weather")
            }, { error ->
                // 处理错误
                Log.e("WeatherViewModel", "Error fetching weather: ${error.message}")
                _weather.value = null
            })

            // 将请求添加到队列中
            queue.add(stringRequest)
        }
    }
    // 从 raw 资源目录中读取文件内容
    fun readFileFromRaw(context: Context, rawName: Int): String {
        val inputStream = context.resources.openRawResource(rawName)
        Log.d("MusicPlayerScreen", "LaunchedEffect executed")
        return inputStream.bufferedReader().use { it.readText() }
    }
}